Ext.namespace("Ext.qd");
Ext.namespace("Ext.qd.nzb");


Ext.qd.nzb.chooseMovie = function (record){
  var expander = new AjaxRowExpander({
    tpl             : new Ext.Template(
			            '<table>' +
			            '  <tr><td colspan="2"><b>{title}</b> <i>{director}</i>({year})</td></tr>' +
			            '  <tr><td>{plot}</td><td><img src="{poster}" width="100"></td>' +
			            '</table>'),
      previewURL    : 'proxy.php',
      params        : {
        exw_action      : 'QDNzbProxy.chooseMoviesDetail'
      },
      extraParamsCallback : function(){
      	return {engine     : Ext.getCmp('cmbchoosemovieengine').getValue()};
      },
      idColumn      : 'id',
      AjaxIdColumn  : 'id'
    });
    
  var sm = new Ext.grid.CheckboxSelectionModel();
  var win = new Ext.Window({
    width:700,
    height:600,
    modal : true,
    layout : 'border',
    items : [{
      xtype : 'panel',
      region : 'north',
      layout : 'table',
      frame : true,     
      height : 35,
      items : [{
        html  :'Movies :&nbsp;'        
      },{
        xtype : 'textfield',        
        id    : 'textchoosemovies',
        width : 250,    
        value : record.data.title,           
        enableKeyEvents : true,
          height    : 20,
          listeners: { 
            keypress: function(ob,e){
              if (e.getCharCode()==13){
                Ext.getCmp('butchoosemovies').events.click.listeners[0].fn();
              }
            }
          }      
      },{
      	xtype : 'combo',
      	id    :'cmbchoosemovieengine',
        store: new Ext.data.SimpleStore({
          fields: ['engine'],
            data : [['SpeedAllocine'],['TheMovieDB']] 
        }),
        displayField  :'engine',
        valueField    :'engine',
        typeAhead     : true,
        mode          : 'local',
        forceSelection: true,
        triggerAction : 'all',
        emptyText     :'Select an engine...',
        selectOnFocus :true,
        listeners : {
          select : function(a,b,c){
          	Ext.qd.lastMovieEngine=b.data.engine;
          }
        },
      },{
        xtype : 'button',
        text  : 'search',
        id    : 'butchoosemovies',
        listeners :{
          click :  function(){
            Ext.getCmp('gridchoosemovies').store.load({
              params : {
                m : Ext.getCmp('textchoosemovies').getValue(),
                engine     : Ext.getCmp('cmbchoosemovieengine').getValue()
              } 
            });
          }
        }
      }]
    },{
      xtype  : 'grid',
      region : 'center',
      id     : 'gridchoosemovies',
      height : 200,
      loadMask: true,
      viewConfig: {
        forceFit: true
      },
      store  : new Ext.data.JsonStore({
        url      : 'proxy.php',
        pruneModifiedRecords:true,        
        baseParams : {
          exw_action : 'QDNzbProxy.chooseMovies'            
        },
        root   : 'results',
        fields : [
           'title',
           'url',
           'id'
        ],
        listeners :{ 
          load : function (r){
            if (r.data.items){
              Ext.getCmp('gridchoosemovies').getSelectionModel().selectRow(0)
            }
          }
        }
      }),
      selectionModel : sm,
      plugins : expander,
      columns: [
        expander,
        sm,
        {id    : 'title1',header: "title" , dataIndex: 'title' , sortable: true},          
        {header: "id"   , width :  90     , dataIndex: 'id'    , sortable: true, fixed : true}          
      ]          
    }],
    buttons :[{ 
      text : 'ok',
      handler : function(){
        var recordSelected = Ext.getCmp('gridchoosemovies').getSelectionModel().getSelected();
        if (!recordSelected || !recordSelected.data.id){
              Ext.ux.Toast.msg('Erreur','aucun film selectionné')
              return;   
        }
        if (recordSelected){
          //var w = Ext.MessageBox.wait('mise à jour');
          Ext.Ajax.request({
            url    : 'proxy.php',
            params : {
              exw_action : 'QDNzbProxy.setMoviesFromPath',
              p          : record.data.pathfilename64,
              i          : recordSelected.data.id,
              title      : recordSelected.data.title,
              engine     : Ext.getCmp('cmbchoosemovieengine').getValue(),
              onlyRenameMovies : (Ext.getCmp('onlyRenameMovies').pressed?1:0)
            },
            success : function(r){
              var r = Ext.util.JSON.decode(r.responseText)
              Ext.getCmp('gridchoosemovies').store.remove(recordSelected);
              Ext.ux.Toast.msg('mise à jour','fichier traité')
              //w.hide();
            }         
          });
          win.hide();
        }else{
          Ext.MessageBox.alert('Error','rien de selectionné');
        }
      }    
    },{ 
      text : 'cancel',
      handler : function(){
        win.close();
      }   
    }],
    listeners : {
      show  : function(){
      	if (!Ext.qd.lastMovieEngine) Ext.qd.lastMovieEngine = 'SpeedAllocine';
      	console.log(Ext.qd.lastMovieEngine );
      	Ext.getCmp('cmbchoosemovieengine').setValue(Ext.qd.lastMovieEngine);
        Ext.getCmp('gridchoosemovies').store.load({
          params : {
            m : Ext.getCmp('textchoosemovies').getValue(),
            engine     : Ext.getCmp('cmbchoosemovieengine').getValue()
          } 
        });
      }
    }
  })
  win.show();
}

Ext.qd.nzb.loadMoviesFilesGrid = function(pathname ){
  Ext.getCmp('gridmoviesfiles').pathname = pathname ; 
  Ext.getCmp('gridmoviesfiles').store.removeAll()
  Ext.getCmp('gridmoviesfiles').store.load({
    params :{
      fullpath : pathname,
      only2Rename:Ext.getCmp('onlyRenameMovies').pressed      
    }     
  });
}
Ext.qd.nzb.clickOnMoviesTreeFolderNode = function(node){
    if (Ext.getCmp('folderMoviesTree').getSelectionModel().isSelected(node)){
      if(node.attributes.fullname!=-1){
        Ext.qd.nzb.loadMoviesFilesGrid(node.attributes.fullname);
      }
    }
  }
  
  
  
Ext.qd.nzb.MoviesPanel = Ext.extend(Ext.Panel, {
  initComponent : function() {
        this.expander = new Ext.grid.RowExpander({
          tpl : new Ext.Template('{Overview}')
        });
       this.cellActions = new Ext.ux.grid.CellActions({
        callbacks:{
         'tree-icon-application-go':function(grid, record, action, value) {
             //Ext.ux.Toast.msg('Callback: icon-undo', 'You have clicked: <b>{0}</b>, action: <b>{1}</b>', value, action);
             Ext.qd.nzb.chooseMovie(record);
         },
         'tree-icon-view-movie': function(grid, record, action, value){
         	//console.log(grid, record, action, value);
         	VLCOpenVideo(Ext.util.base64.decode(record.data.uncfilename64),record.data.title);
         }
       }
       ,align:'left'
       });    
        var sm = new Ext.grid.CheckboxSelectionModel();
        Ext.apply(this,{
          layout    : 'border',
          items     : [{
            xtype     : 'tabpanel',
            region    :'west',
            activeTab : 0,
              width   : 300,      
            items : [{
              xtype     : 'columntree',
              title     : 'Movies folders',
              id        : 'folderMoviesTree',
              loadMask  : true,      
              split     : true,
              rootVisible:false,
              lines     : true,
              selModel  : new Ext.tree.MultiSelectionModel(),
              fitToFrame: true,    
              autoScroll:true, 
              containerScroll: true,
              listeners : {
                click : Ext.qd.nzb.clickOnMoviesTreeFolderNode  
              },
              root      : new Ext.tree.AsyncTreeNode({
                text         : 'drives',
                fullfilename : -1,
                draggable    : false
              }),
              tbar            : [{
                  text            : 'refresh',
                  handler         : function(){
                    var ftree = Ext.getCmp('folderMoviesTree');
                    ftree.loader.baseParams.refresh = 1; 
                    ftree.loader.load(ftree.getRootNode());
                  }
                }],
              columns:[{
                    header:'folder',
                    width:200,
                    dataIndex:'text'
                },{
                    header    :'OK',
                    width     :32,
                    dataIndex :'tvdb',
                    renderer  : function (a,b,c){
                      return (b.attributes.tvdb?'<img src="skins/resources/tvdb.jpg">':'');
                    }
                }],
                loader: new Ext.tree.TreeLoader({
                dataUrl:'proxy.php?exw_action=QDNzbProxy.getMoviesTree',
                //dataUrl:'cache/column-data.json',
                uiProviders:{
                  'col': Ext.tree.ColumnNodeUI
                }
              })            
            }]  
          },{
            xtype : 'tabpanel',
              region : 'center',
            activeTab : 0,
                deferredRender :false,
            items : [{
              xtype : 'editorgrid',
              id     : 'gridmoviesfiles',
              title  : 'Files',
              loadMask: true,
              selModel : sm,
              tbar : [{
                text    : 'Select all',
                handler : function(){
                  Ext.getCmp('gridmoviesfiles').getSelectionModel().selectAll();
                } 
              },{
                text    : 'Only to rename',
                id      : 'onlyRenameMovies',
                enableToggle   : true,
                pressed : false
              },{
                text : 'Rename',
                handler : function(){
                  var arrModified = Ext.getCmp('gridmoviesfiles').getStore().data.items;
                  var arrModified = Ext.getCmp('gridmoviesfiles').getSelectionModel().selections.items;
                  var pathname    = Ext.util.base64.encode(Ext.getCmp('gridmoviesfiles').pathname);
                  var arrResult = {
                    modified : {}                
                  };
                  Ext.each(arrModified,function(v,k){
                    if (!arrResult.modified[pathname]) arrResult.modified[pathname]=[];
                    arrResult.modified[pathname].push({
                      'new64'  : Ext.util.base64.encode((v.data.newfilename+' ').trim()),                
                      'ext'    : v.data.ext,                
                      'md5'    : v.data.md5
                    });
                  });
                  console.log(arrResult);
                  Ext.Ajax.request({
                    url      : 'proxy.php',
                    params : {
                      exw_action : 'QDNzbProxy.renameMoviesFiles',
                      modified   : Ext.util.base64.encode(Ext.util.JSON.encode(arrResult))
                    },
                    success : function(r){
                      Ext.qd.nzb.loadMoviesFilesGrid(Ext.getCmp('gridmoviesfiles').pathname);
                    }
                  });
                }  
              },{
                text    : 'Un-Select all',
                handler : function(){
                  Ext.getCmp('gridmoviesfiles').getSelectionModel().clearSelections();
                } 
              },{
                text    : 'Invert Selection',
                handler : function(){
                  alert('to do');
                } 
              }],
              clicksToEdit : 1,
              store: new Ext.data.JsonStore({
                  url      : 'proxy.php',
                  baseParams : {
                    exw_action : 'QDNzbProxy.getMoviesFiles'            
                  },
                  root: 'results',
                  pruneModifiedRecords  : true,
                  fields: [
                     {name: 'oldfilename'   },
                     {name: 'newfilename'   },
                     {name: 'title'         },
                     {name: 'ext'           },
                     {name: 'filesize'      },
                     {name: 'pathfilename64'},                 
                     {name: 'uncfilename64' },                                  
                     {name: 'Overview'      },
                     {name: 'md5'           }             
                  ],
                  listeners : {
                      datachanged  :function(){
                        console.log(this);
                     }
                  }
              }),
              plugins : [this.expander,this.cellActions],
               listeners : {
                 rowdblclick : function(a,b,c){
                   console.log(a,b,c);
                   //VLCOpenVideo('file://zutzut/m/___Films/A%20Man%20Called%20Hero/A%20man%20called%20hero.avi')   
                 }
               },
              columns: [
                  sm,
                  this.expander,      
                  {header: "rename"    , width:   280, dataIndex: 'newfilename' , sortable: true,editor:new Ext.form.TextField({allowBlank:false})},
                  {header: "title"     , width:   300, dataIndex: 'title'       , sortable: true,cellActions:[{
		               iconCls:'tree-icon-application-go',
		               qtip:'select the movie',
		               hide:true,
		               hideMode:'display'
		               },{
		               iconCls:'tree-icon-view-movie',
		               qtip:'view the movie',
		               hide:true,
		               hideMode:'display'
		           }],
               },          
                  {header: "File Name" , width:   300, dataIndex: 'oldfilename' , sortable: true},          
                  {header: "Type"      , width:    40, dataIndex: 'ext'         , sortable: true},          
                  {header: "Size"      , width:    80, dataIndex: 'filesize'    , sortable: true}
                            
              ]
            }]
        }]
      })
      
      Ext.qd.nzb.MoviesPanel.superclass.initComponent.apply(this, arguments);
  }  
});
Ext.reg('nzb.moviePanel',Ext.qd.nzb.MoviesPanel)





VLCOpenVideo = function (url,title){
	
    var VLCPlayerPanel = new Ext.ux.VlcPlayer({
        playerId     : 'myplayer'+Ext.id(),
        verbosity   : 2
    });
    
    /*VLCPlayerPanel.on('ready', function(panel, player) {
        panel.dolog("player ready");
    }, VLCPlayerPanel);*/        
        
   var wVLCPlayerPanel = new Ext.Window({
        title        : '['+title+']',
        hideMode     : 'visibility',
        layout       : 'fit',
        maximizable  : false,
        animCollapse : false,
        collapsible  : false,
        closable     : true,
        resizable    : true,
        items        : [VLCPlayerPanel],
        bbar         : new Ext.ux.VlcPlayer.Control({
            player       : VLCPlayerPanel,
            border       : false,
            //id           : 'control',
            style        : 'border:none;'
        }),
        listeners   : {
            resize   : function(){
            	this.bottomToolbar.fireEvent('resize')
            },
            show: function(){
                window.onVlcPlayerReady(VLCPlayerPanel.playerId);
                VLCPlayerPanel.playVideo(url, url, ":http-caching=5000");
            },
             beforeclose  : function(){
             	VLCPlayerPanel.stopVideo();
                console.log('eeeeeee');
            }
        },
        height      : 400,
        width       : 500
    });     
     wVLCPlayerPanel.show();           
     
}
